package com.hmall.search.task;

import cn.hutool.json.JSONUtil;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.FiltersDto;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/*
 *   Description HotTask
 *   @author zhangyan
 *   @time   2024/11/14
 */
@Component
@RefreshScope
public class HotTask {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private StringRedisTemplate redisTemplate;
//    @Value("${cron}")
//    private String cron;
    //每天3点预热热搜
    @Scheduled(cron = "0 0 3 * * ? ")
    public void execute() {
        FiltersDto filtersDto = FiltersDto.builder()
                .sortBy("default")
                .page(1)
                .size(20)
                .build();
        PageDTO<Item> pageDTO = itemClient.searchByCondition(filtersDto);
        ArrayList<Item> items = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
          items.add(pageDTO.getList().get(i));
        }
        PageDTO<Item> pageDTO1 = new PageDTO<>();
        pageDTO1.setTotal(pageDTO.getTotal());
        pageDTO1.setList(items);
        redisTemplate.opsForValue().set("hotItems", JSONUtil.toJsonStr(pageDTO1),24, TimeUnit.HOURS);
    }
}
